package cn.ronghuanet.base.service.impl;

import cn.ronghuanet.base.service.IFastdfsService;
import cn.ronghuanet.base.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FastdfsServiceImpl implements IFastdfsService {

    @Value("${ronghua.fastdfs.prefixUrl}")
    private String prefixUrl;

    @Override
    public String upload(MultipartFile file) throws Exception{
        // 1 获取文件名
        String filename = file.getOriginalFilename();
        // 2 获取文件后缀名
        String extension = FilenameUtils.getExtension(filename);

        // 3 将文件上传到fastdfs
        byte[] bytes = file.getBytes();
        String fastDfsUrl = FastdfsUtil.upload(bytes, extension);
        return this.prefixUrl+fastDfsUrl;
    }

    /**
     * http://115.159.217.249:8888//group1/M00/00/4E/rBEAA2Td3WCAOoUfAAf5YDoD9t4972.png
     * /group1/M00/00/4E/rBEAA2Td3WCAOoUfAAf5YDoD9t4972.png
     * @param path
     */
    @Override
    public void delete(String path) {
        // 要将前端传递的url转换为group路径
        // 方式一  截取  path.sub(this.prefixUrl.length)
        // 方式二  替换,将前缀替换为空字符串
        path = path.replace(this.prefixUrl,"");
        FastdfsUtil.delete(path);
    }
}
